﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Net;
using XKSocket;

namespace ServerTestor
{
    public class PlayerServer
    {
        PlayerServer() { }
        public static PlayerServer Instance
        {
            get { return GetSingleton.instance; }
        }
        class GetSingleton
        {
            static GetSingleton() { }
            internal static readonly PlayerServer instance = new PlayerServer();
        }

        public XKServer Skt=null;
        public Hashtable htConnItem = new Hashtable();

        public bool Start(string IP,int port)
        {
            try
            {
                this.Skt = new XKServer(IPAddress.Parse(IP.Trim()), port);
                this.Skt.OnConnected += Skt_OnConnected;
                this.Skt.OnDataRecv += Skt_OnDataRecv;
                this.Skt.OnDisConnected += Skt_OnDisConnected;
                this.Skt.Start();
            }
            catch
            {
                return false;
            }
            return true;
        }
        public void ShutDown()
        {
            this.Skt.Shutdown();
        }

        void Skt_OnConnected(object sender, SktEventArgs e)
        {
            PlayerItem PlyItem = new PlayerItem(e.Conn);
            this.htConnItem.Add(e.Conn.ConnectionID, PlyItem);
        }
        void Skt_OnDataRecv(object sender, SktDataRecvEventArgs e)
        {
            PlayerMsgDispatcher.Instance.MsgDispatch(this.htConnItem[e.Conn.ConnectionID] as PlayerItem, e.Data);
        }
        void Skt_OnDisConnected(object sender, SktEventArgs e)
        {
            PlayerItem PlyItem = this.htConnItem[e.Conn.ConnectionID] as PlayerItem;
            if (PlyItem != null)
            {
                PlyItem.ShowDisConnected();
            }
            this.htConnItem.Remove(e.Conn.ConnectionID);
        }
    }
}
